package com.bsj.travel.security.handler;

import com.bsj.travel.def.global.JsonResult;
import com.bsj.travel.def.global.JsonResultEnum;
import com.bsj.travel.exception.ApiException;
import com.bsj.travel.exception.InnerAuthException;
import com.bsj.travel.exception.auth.NotPermissionException;
import com.bsj.travel.exception.auth.NotRoleException;
import com.bsj.travel.util.ExceptionUtil;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yinhao
 * @version 1.0
 * @description 全局异常处理
 * @date 2023/11/1
 */
@RestControllerAdvice
@Slf4j
@Order(-1)
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public JsonResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址{}，不支持：{} 请求", requestURI, e.getMethod());
        return JsonResult.fail(e.getMessage());
    }

    /**
     * 自定义业务异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ApiException.class)
    public JsonResult handleApiException(ApiException e, HttpServletRequest request) {
        JsonResultEnum status = e.getStatus();
        return JsonResult.fail(status);
    }

    /**
     * 拦截未知的运行时异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public JsonResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String eMessage = e.getMessage();
        log.error("请求地址： {}， 发生未知异常: {}", requestURI, ExceptionUtil.getStackStr(e));
        if (eMessage != null && e.getMessage().contains("Required request body is missing")) {
            //参数转换异常
            return JsonResult.fail(JsonResultEnum.PARAM_CAST_EXCEPTION);
        }
        if (eMessage != null && e.getMessage().contains("FeignException$ServiceUnavailable")) {
            //参数转换异常
            return JsonResult.fail(JsonResultEnum.FEIGN_SERVICE_EXCEPTION);
        }
        return JsonResult.fail(e.getMessage());
    }

    /**
     * 内部服务调用异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(FeignException.class)
    public JsonResult handleFeignException(FeignException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String eMessage = e.getMessage();
        log.error("请求地址： {}, 内部服务调用异常： {},", requestURI, ExceptionUtil.getStackStr(e));
        //参数转换异常
        return JsonResult.fail(JsonResultEnum.FEIGN_SERVICE_EXCEPTION);
    }

    /**
     * 系统异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址： {}， 发生系统异常: {}", requestURI, ExceptionUtil.getStackStr(e));
        return JsonResult.fail(e.getMessage());
    }

    /**
     * 内部认证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(InnerAuthException.class)
    public JsonResult handleInnerAuthException(InnerAuthException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址： {}， 内部认证异常", requestURI);
        return JsonResult.fail(e.getStatus());
    }

    /**
     * 权限码异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(NotPermissionException.class)
    public JsonResult handlerNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址： {}, 权限码校验失败：{}", requestURI, e.getMessage());
        return JsonResult.fail(JsonResultEnum.PERMISSION_EXCEPTION);
    }

    /**
     * 角色权限异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(NotRoleException.class)
    public JsonResult handlerNotRoleException(NotRoleException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址： {}, 角色权限校验失败：{}", requestURI, e.getMessage());
        return JsonResult.fail(JsonResultEnum.PERMISSION_EXCEPTION);
    }

    /**
     * 参数校验返回
     *
     * @param e
     * @param request
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = BindException.class)
    public JsonResult bindExceptionErrorHandler(BindException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址： {}, 角色权限校验失败：{}", requestURI, e.getMessage());
        StringBuilder stringBuilder = new StringBuilder();
        FieldError fieldError = e.getFieldError();
        stringBuilder.append(fieldError.getDefaultMessage());
        return JsonResult.fail(JsonResultEnum.PARAM_ERROR, stringBuilder.toString());
    }

}
